<?php

$di = \application\units\Di::getInstance();

$params = [
    'admin_id' => $di->auth->id,
    'role_id'  => $di->request->params('role_id'),
    'email'    => $di->request->params('email'),
    'username' => $di->request->params('username'),
    'nickname' => $di->request->params('nickname'),
    'password' => $di->request->params('password'),
    'avatar'   => $di->request->params('avatar', ''),
];

$roleIds = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);

if (false === \filter_var($params['email'], FILTER_VALIDATE_EMAIL)) throw new LogicException('邮箱格式错误');
if ('' == $params['nickname']) throw new LogicException('昵称不能为空');
if (0 == preg_match('/^[a-zA-Z][a-zA-Z0-9]{5,19}$/', $params['username'])) throw new LogicException('账号只能以字母开头，长度为6-20');
if (strlen($params['password']) < 6) throw new LogicException('密码不能小于6位');
if (empty($roleIds)) throw new LogicException('角色组不能为空');

// 判断邮箱是否存在
$hasEmail = $di->db->find('select * from admin where email=:email', [
    'email' => $params['email'],
]);
if ($hasEmail) throw new LogicException('邮箱已存在');

// 判断账号是否存在
$hasUsername = $di->db->find('select * from admin where username=:username', [
    'username' => $params['username'],
]);
if ($hasUsername) throw new LogicException('账号已存在');

if ($params['admin_id'] != "") {
    if (array_diff($roleIds, $di->auth->getChildrenRoleIds($params['admin_id']))) {
        throw new LogicException('只能选择自己角色组下面的角色');
    }
}

$salt     = substr(md5(random_bytes(32)), 0, 6);
$password = md5(md5($params['password']) . $salt);
try {
    $di->db->beginTransaction();
    
    // 添加管理员
    $stat = $di->db->execute('insert into admin(email, username, nickname, password, salt, avatar, create_time, update_time)
                      values (:email, :username, :nickname, :password, :salt, :avatar, :create_time, :update_time)', [
        'email'       => $params['email'],
        'username'    => $params['username'],
        'nickname'    => $params['nickname'],
        'password'    => $password,
        'salt'        => $salt,
        'avatar'      => $params['avatar'],
        'create_time' => date('Y-m-d H:i:s'),
        'update_time' => date('Y-m-d H:i:s'),
    ]);
    
    if ($stat->rowCount() <= 0) throw new PDOException('添加管理员失败');
    
    $id = $di->db->lastInsertId();
    
    // 添加管理员角色
    foreach ($roleIds as $roleId) {
        $stat = $di->db->execute('insert into admin_role_access(admin_id, role_id, update_time, create_time)
                          values (:admin_id, :role_id, :update_time, :create_time)', [
            'admin_id'    => $id,
            'role_id'     => $roleId,
            'update_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
        ]);
        if ($stat->rowCount() <= 0) throw new LogicException('添加管理员角色失败');
    }
    
    $di->db->commit();
} catch (\Exception $e) {
    $di->db->rollback();
    throw $e;
}

return [
    'row' => [
        'id' => $id,
    ],
];